<template>
  <DatePicker v-model:value="value"></DatePicker>
</template>
<script setup lang="ts">
import { DatePicker, Form } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';

import { ref, watch } from 'vue';
const model = defineModel<string>('value');
const props = withDefaults(defineProps<{ format?: string }>(), {
  format: 'YYYY-MM-DD',
});
const value = ref<Dayjs>();

const formItemContext = Form.useInjectFormItemContext();

watch(
  model,
  () => {
    if (model.value && value.value) {
      if (model.value != value.value.format(props.format)) {
        value.value = dayjs(model.value);
      }
    } else {
      value.value = model.value ? dayjs(model.value) : undefined;
    }
  },
  {
    immediate: true,
  }
);
watch(model, () => {
  formItemContext.onFieldChange();
});
watch(value, (v) => {
  if (v) {
    model.value = v.format(props.format);
  } else {
    model.value = undefined;
  }
});
</script>
<style module lang="scss"></style>
